﻿//----------------------------------------------------------------
// Copyright (C) 2011-2012 TaoSys软件有限责任公司
// All rights reserved.
//
// 文件名：AccessBase.cs
// 摘  要：数据访问基础类
// 说  明：提供统一通用的CRUD数据实体操作
//

//当前版本：1.0
//作    者：陶剑扬
//完成日期：2011-07-09
//----------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Data;
using System.Data.Entity;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Data.EntityClient;

using PowerSys.Model;

namespace PowerSys.DataAccess
{
    public abstract class AccessBase
    {
        protected XBase Context { get; set; }

        /// <summary>
        /// 抽象属性EntitySetName，延迟到子类实现
        /// </summary>
        protected abstract string EntitySetName { get; }

        /// <summary>
        /// 添加实体
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="entity">实体</param>
        public void Add<T>(T entity)
        {
            Submit(entity, EntityState.Added);
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="entity">实体</param>
        public void Update<T>(T entity)
        {
            Submit(entity, EntityState.Modified);
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="entity">实体</param>
        public void Delete<T>(T entity)
        {
            Submit(entity, EntityState.Deleted);
        }

        /// <summary>
        /// 提交更改
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="entity">实体</param>
        /// <param name="entityState">实体状态</param>
        private void Submit<T>(T entity, EntityState entityState)
        {
            using (XBase xb = new XBase())
            {
                Context = xb;
                //先将实体附加到实体上下文中
                //xb.X_User.Attach(x_user);
                //xb.AddObject();
                //xb.ApplyCurrentValues();
                xb.AddObject(EntitySetName, entity);
                //手动修改实体的状态
                xb.ObjectStateManager.ChangeObjectState(entity, entityState);
                //保存回数据库
                xb.SaveChanges();
            }
        }
    }
}
